package controllers

import (
	"weiboxs.com/new_h_glasses/enums"
	"weiboxs.com/new_h_glasses/models"
	"weiboxs.com/new_h_glasses/utils"
)

type DepartmentController struct {
	BaseController
}

func (c *DepartmentController) Prepare() {
	//先执行
	c.BaseController.Prepare()
	c.Data["activeSidebarUrl"] = "/department/index"
}

func (c *DepartmentController) Index() {
	c.checkAuthor("department/index") //需要权限控制
	c.display("", "department/index_footerjs.html")
}

func (c *DepartmentController) DataGrid() {

	c.checkAuthor("department/index") //需要权限控制

	//获取数据列表和总数
	data := models.DepartmentDataList()

	c.jsonDataTable(0, data)
}

func (c *DepartmentController) GetDepListForManage() {
	//获取数据列表和总数
	data := models.DepartmentDataList(c.curUser.ExtendDepartmentList)
	c.jsonResult(enums.JRCodeSucc, "ok", data)
}

func (c *DepartmentController) Delete() {

	c.checkAuthor("department/action") //需要权限控制

	id, err := c.GetInt64("id")
	if err != nil {
		c.jsonResult(enums.JRCodeFailed, "出错了", "")
	}

	if err := models.DepartmentDeleteById(id); err != nil {
		c.jsonResult(enums.JRCodeFailed, "出错了", "")
	}

	c.jsonResult(enums.JRCodeSucc, "操作成功", "")
}

func (c *DepartmentController) Edit() {

	c.checkAuthor("department/action") //需要权限控制

	if c.Ctx.Request.Method == "POST" {
		c.Save()
	}

	Id, _ := c.GetInt(":id", 0)

	m := models.Department{Id: int64(Id)}
	if Id > 0 {
		gm, err := models.GetDepartmentById(int64(Id))
		if err != nil {
			c.pageError("数据无效，请刷新后重试")
		}
		c.Data["m"] = gm
	} else {
		c.Data["m"] = m
	}

	c.display("", "department/edit_footerjs.html", "shared/layout_dialog.html")
}

//Save 添加、编辑页面 保存
func (c *DepartmentController) Save() {
	var err error
	m := models.Department{}
	//获取form里的值
	if err = c.ParseForm(&m); err != nil {
		c.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}
	if m.Id == 0 {
		if _, err = models.DepartmentAdd(&m); err == nil {
			c.jsonResult(enums.JRCodeSucc, "添加成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}

	} else {
		f,_ := utils.ReflectModelFields(&m)
		if err = m.DepartmentEdit(f...); err == nil {
			c.jsonResult(enums.JRCodeSucc, "编辑成功", m.Id)
		} else {
			c.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
	}
}
